<!DOCTYPE html>
<html lang="zh">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>gsap动画库</title>
  </head>
  <body>
    <script type="module">
      // 引入three.js
      import * as THREE from "three";
      import { scene, camera, renderer, controls } from "/src/utils/init.js";
      //引入gsap动画库
      import gsap from "gsap";

      // 创建地面
      function createFloor() {
        camera.position.set(5, 5, 5);
        // 1.创建平面缓冲几何体
        const geometry = new THREE.PlaneGeometry(10, 10);
        const material = new THREE.MeshStandardMaterial({
          color: 0xffffff,
          side: THREE.DoubleSide,
        });
        const plane = new THREE.Mesh(geometry, material);
        plane.receiveShadow = true;
        plane.rotation.set(-Math.PI / 2, 0, 0);
        scene.add(plane);
      }

      // 创建小球
      let sphere;
      function createSphere() {
        const geometry = new THREE.SphereGeometry(1, 32, 16);
        const material = new THREE.MeshStandardMaterial({
          color: 0x00ff00,
        });
        sphere = new THREE.Mesh(geometry, material);
        sphere.position.set(0, 1, 0);
        sphere.castShadow = true;
        scene.add(sphere);
      }

      // 创建光源
      let directionLightHelper; // 平行光辅助对象
      function createLight() {
        //平行光
        const directionalLight = new THREE.DirectionalLight(0xffffff, 1);
        directionalLight.position.set(3, 3, 3);
        directionalLight.castShadow = true;
        directionalLight.target = sphere; // 让平行光指向小球
        scene.add(directionalLight);

        // 平行光辅助对象
        directionLightHelper = new THREE.DirectionalLightHelper(
          directionalLight,
          1
        );
        scene.add(directionLightHelper);
      }

      // 加载动画
      function initAnimation() {
        // 使用 gsap.to() 做一个补间动画
        const aniObj = gsap.to(sphere.position, {
          x: 5, // 属性变化
          duration: 3, // 动画持续时间
          delay: 1, // 延迟时间
          repeat: -1, // 为-1时无限次反复运动
          yoyo: true, // 回到原点也有一个动画
          ease: "bounce", // 缓冲效果 （参考：https://greensock.com/docs/Eases)
          onStart() {
            // console.log("开始动画");
          },
          onUpdate() {
            directionLightHelper.update(); // 让平行光辅助对象可以实时更新角度和射线
          },
          onComplete() {
            // console.log("动画结束");
          },
        });
        // 控制动画的暂停/回复
        window.addEventListener("dblclick", () => {
          if (aniObj.isActive()) {
            // 当前动画运动中时，isActive()为true
            aniObj.pause(); // 暂停
          } else {
            aniObj.resume(); // 恢复
          }
        });
      }

      camera.position.set(5, 5, 5);
      renderer.shadowMap.enabled = true;

      createFloor();
      createSphere();
      createLight();
      initAnimation();
    </script>
  </body>
</html>
